package com.cby.android.olive.utils

import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.content.pm.Signature
import java.lang.StringBuilder
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException

object SignUtils {


    const val SHA1 = "SHA1"

    /**
     * 返回一个签名的对应类型的Sha1字符串
     *
     * @param context
     */
    @JvmStatic
    fun getSignInfo(context: Context): String? {
        val packageName = context.applicationContext.packageName
        val signs = getSignatures(context, packageName)
        return getSignatureString(signs!![0], SHA1)
    }

    /**
     * 获取指定包名的应用的签名
     *
     * @param context Context
     * @param packageName String?
     * @return String?
     */
    @JvmStatic
    fun getSignature(context: Context, packageName: String?):String?{
        val signs = getSignatures(context, packageName)
        if(signs != null) {
            return getSignatureString(signs[0], SHA1)
        }
        return null
    }

    /**
     * 返回对应包的签名信息
     *
     * @param context
     * @param packageName
     * @return
     */
    @JvmStatic
    @SuppressLint("PackageManagerGetSignatures")
    private fun getSignatures(context: Context, packageName: String?): Array<Signature>? {
        var packageInfo: PackageInfo?
        try {
            packageInfo = context.packageManager
                .getPackageInfo(packageName!!, PackageManager.GET_SIGNATURES)
            return packageInfo.signatures
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        return null
    }


    /**
     * 获取相应的类型的字符串（把签名的byte[]信息转换成16进制）
     *
     * @param sig
     * @param type
     * @return
     */
    private fun getSignatureString(sig: Signature, type: String?): String? {
        val hexBytes = sig.toByteArray()
        var fingerprint = "error!"
        try {
            val digest = MessageDigest.getInstance(type)
            if (digest != null) {
                val digestBytes = digest.digest(hexBytes)
                val sb = StringBuilder()
                for (digestByte in digestBytes) {
                    val i :Int = digestByte.toInt() and 0xFF or 0x100
                    sb.append(Integer.toHexString(i).substring(1, 3))
                }
                fingerprint = sb.toString()
            }
        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
        }
        return fingerprint
    }

}